package com.husd.framework.ddl;

import com.husd.framework.code.DDLColumn;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shengdonghu@126.com
 * @date 2023/10/7 11:23
 */
public class MapperXmlUtil {

    public static String getAllColumn4UpdateValue(DDL ddl) {
        List<String> stringList = new ArrayList<>();
        for (DDLColumn ddlColumn : ddl.getColumnList()) {
            stringList.add("`" + ddlColumn.getColumnName() + "` = #{" + ddlColumn.getColumnNameLowerCamel() + "}");
        }
        String res = String.join(",", stringList);
        return res;
    }

    public static String getAllColumn4InsertValue(DDL ddl) {

        List<String> stringList = new ArrayList<>();
        for (DDLColumn ddlColumn : ddl.getColumnList()) {
            stringList.add("#{" + ddlColumn.getColumnNameLowerCamel() + "}");
        }
        String res = String.join(",", stringList);
        return res;
    }

    public static String getAllColumn(DDL ddl) {

        List<String> stringList = new ArrayList<>();
        for (DDLColumn ddlColumn : ddl.getColumnList()) {
            stringList.add("`" + ddlColumn.getColumnName() + "`");
        }
        String res = String.join(",", stringList);
        return res;
    }

    public static String getResultMap(DDL ddl) {

        StringBuilder sb = new StringBuilder();
        for (DDLColumn ddlColumn : ddl.getColumnList()) {
            sb.append("<result column=\"");
            sb.append(ddlColumn.getColumnName());
            sb.append("\" property=\"");
            sb.append(ddlColumn.getColumnNameLowerCamel());
            sb.append("\"/>\n");
        }
        return sb.toString();
    }

    public static String getSelect4Where(DDL ddl) {

        String t1 = "<if test = \"%s != null and %s !=''\" >";
        String t2 = "<if test = \"%s != null \" >";

        String t3 = "and `%s` = #{%s}";

        StringBuilder sb = new StringBuilder();
        for (DDLColumn ddlColumn : ddl.getColumnList()) {
            if (StringUtils.equalsIgnoreCase(ddlColumn.getColumnType4Java(), "String")) {
                String s = String.format(t1, ddlColumn.getColumnNameLowerCamel(),
                        ddlColumn.getColumnNameLowerCamel());
                sb.append(s).append("\n");
            } else {
                String s = String.format(t2, ddlColumn.getColumnNameLowerCamel());
                sb.append(s).append("\n");
            }
            String tt3 = String.format(t3, ddlColumn.getColumnName(),
                    ddlColumn.getColumnNameLowerCamel());
            sb.append(tt3).append("\n");
            sb.append("  </if>");
        }
        return sb.toString();
    }
}
